import { create } from 'zustand'
import { usernamePasswordLogin, UsernamePasswordLoginPayload } from '../apis/auth'
import { Me, getMe } from '../apis/me'

type MeState = {
  status: { state: "AUTHED", me: Me } | { state: "UNAUTHED" } | { state: "LOADING" },
  login: (payload: UsernamePasswordLoginPayload) => Promise<void>
  load: () => void
}

export const useMeStore = create<MeState>((set) => ({
  status: { state: "LOADING" },
  login: async (payload: UsernamePasswordLoginPayload) => {
    set({ status: { state: 'LOADING' } })
    try {
      const me = await usernamePasswordLogin(payload)
      set({ status: { state: 'AUTHED', me } })
    } catch (err) {
      console.log("username and password login failed", err) // TODO: 错误处理
      set({ status: { state: "UNAUTHED" } })
    }
  },
  load: async () => {
    set({ status: { state: 'LOADING' } })
    try {
      const me = await getMe()
      set({ status: { state: 'AUTHED', me } })
    } catch (err) {
      console.log("load me failed", err) // TODO: 错误处理
      set({ status: { state: "UNAUTHED" } })
    }
  }
}))